/*
 * Copyright (C) 2011  John Lawrence thegordo.john at gmail.com
 * Licensed under GPLv3 or later. see http://www.gnu.org/copyleft/gpl.html
 */

package org.jklawrencefam.Util;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User: John Lawrence
 * Date: 5/22/11
 * Time: 7:49 AM
 */
public class LogFactory {
    private static Level myLevel = Level.INFO;
    private static Map<String, Logger> loggerMap = new HashMap<String, Logger>();

    public static void setLevel(Level level) {
        myLevel = level;
        Logger rootLogger = Logger.getLogger("");
        rootLogger.setUseParentHandlers(false);
        if (rootLogger.getHandlers().length == 0) {
            rootLogger.addHandler(new ConsoleHandler());
        }
        for (Handler handler : rootLogger.getHandlers()) {
            handler.setLevel(level);
        }
        rootLogger.setLevel(myLevel);
    }

    public static Logger getLogger(Class type) {
        return getLogger(type.getName());
    }

    public static Logger getLogger(String name) {
        Logger logger = loggerMap.get(name);
        if (logger == null) {
            return getNewLogger(name);
        }
        return logger;
    }

    private static Logger getNewLogger(String name) {
        Logger logger = Logger.getLogger(name);
        loggerMap.put(name, logger);
        return logger;
    }
}
